package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.media.RingtoneManager
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.DayWorkRecordBean
import com.zat.mes.andrmes.data.ItemList
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.OrderCraftprocessBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.work.adapter.DayWorkScanProcAdapter
import com.zat.mes.andrmes.dofun.work.adapter.DayWorkScanProcAdapter00
import com.zat.mes.andrmes.dofun.work.adapter.WorkRecordProcAdapter
import com.zat.mes.andrmes.dofun.work.vm.WorkRecordViewModel
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_work_scan.*
import org.json.JSONObject
import permissions.dispatcher.*
import java.util.*
import kotlin.collections.ArrayList


/**
 * 横屏 做工
 */
@RuntimePermissions
class DayWorkScanActivity00 : BaseActivity(), View.OnClickListener {


    companion object {
        @JvmStatic
        var DayWorkScanActivityShow: Boolean = false
    }

    private var recordViewModel: WorkRecordViewModel? = null
    private var empName: String = ""
    var day: String = ""
    private var empId: Long = 0
    private var orderId: Long = 0
    private var packId: Long = 0
    /**
     * 所有的下拉数据
     */
    var allStrList: MutableList<ItemList> = ArrayList()
    /**
     * 下拉适配器
     */
    var arrayAdapter: DayWorkScanProcAdapter00? = null
    var listPopupWindow: ListPopupWindow? = null
    /**
     * 日记录bean
     */
    var dayWorkRecordBean: DayWorkRecordBean? = null

    /**
     * 当前的工艺工序
     */
    var procItem: ItemList? = null
    var imgIndex = 1;
    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null

    override fun init() {
        initView()
        addListener()
        initData()
        //读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
//                showLoading()
                if (DayWorkScanActivityShow) {
//                    recordViewModel?.loadPackDataByRFRD(it)
                    val jsonObject = JSONObject()
                    jsonObject.put("empId", empId);
                    jsonObject.put("empName", empName)
                    jsonObject.put("publicRFID",it)
                    //新增 日生产计划
                    recordViewModel?.loadRecordData(jsonObject.toString())
                }
            }
        });
    }

    /**
     * 设备刷卡监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

    /**
     * 添加监听
     */
    private fun addListener() {
        btnRlHideLeft.setOnClickListener(this)
        btnRlShowLeft.setOnClickListener(this)
        btnRlHideArrowdown.setOnClickListener(this)
        btnRlShowArrowdown.setOnClickListener(this)
        btnllBwlf.setOnClickListener(this)
        btnllFzyq.setOnClickListener(this)
        btnllZjyq.setOnClickListener(this)
        btnllProc.setOnClickListener(this)
        llbtnProc.setOnClickListener(this)
        btnScanWork.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            btnRlHideLeft -> {
                //左侧收起
                ObjectAnimator.ofFloat(llLeftWork, "translationX", 0f, -1.0f * llLeftWork.width)
                    .start()
                btnRlShowLeft.visibility = View.VISIBLE
            }
            btnRlShowLeft -> {
                //左侧展开
                ObjectAnimator.ofFloat(llLeftWork, "translationX", -1.0f * llLeftWork.width, 0f)
                    .start()
                btnRlShowLeft.visibility = View.GONE
            }
            btnRlHideArrowdown -> {
                //右侧收起
                ObjectAnimator.ofFloat(llRightWork, "translationY", 0f, -1.0f * llRightWork.height)
                    .start()
                btnRlShowArrowdown.visibility = View.VISIBLE
            }
            btnRlShowArrowdown -> {
                //右侧展开
                ObjectAnimator.ofFloat(llRightWork, "translationY", -1.0f * llRightWork.height, 0f)
                    .start()
                btnRlShowArrowdown.visibility = View.GONE
            }

            //顶部点击
            //部位量法
            btnllBwlf -> {
                ivllBwlf.setBackgroundResource(R.drawable.dw_circel_black)
                ivllBwlf.setImageResource(R.mipmap.buweiliangfa2)
                tvllBwlf.setTextColor(ContextCompat.getColor(baseContext, R.color.color_white))

                ivFzyq.setBackgroundResource(R.color.color_transparent)
                ivFzyq.setImageResource(R.mipmap.fengzhiyaoqiu1)
                tvFzyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivZjyq.setBackgroundResource(R.color.color_transparent)
                ivZjyq.setImageResource(R.mipmap.zhijianyaoqiu1)
                tvZjyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivProc.setBackgroundResource(R.color.color_transparent)
                ivProc.setImageResource(R.mipmap.gongyigongxu1)
                tvProc.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                Glide.with(this)
                    .load(HttpsKitUtils.replaceHttpsUrl(dayWorkRecordBean?.field1?.split(",")?.get(0)))
                    .into(photoViewWork)
                imgIndex = 1
            }
            //缝制要求
            btnllFzyq -> {

                ivFzyq.setBackgroundResource(R.drawable.dw_circel_black)
                ivFzyq.setImageResource(R.mipmap.fengzhiyaoqiu2)
                tvFzyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_white))

                ivZjyq.setBackgroundResource(R.color.color_transparent)
                ivZjyq.setImageResource(R.mipmap.zhijianyaoqiu1)
                tvZjyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivProc.setBackgroundResource(R.color.color_transparent)
                ivProc.setImageResource(R.mipmap.gongyigongxu1)
                tvProc.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivllBwlf.setBackgroundResource(R.color.color_transparent)
                ivllBwlf.setImageResource(R.mipmap.buweiliangfa1)
                tvllBwlf.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))
                Glide.with(this)
                    .load(HttpsKitUtils.replaceHttpsUrl(dayWorkRecordBean?.field2?.split(",")?.get(0)))
                    .into(photoViewWork)
                imgIndex = 2
            }
            //质检要求
            btnllZjyq -> {


                ivZjyq.setBackgroundResource(R.drawable.dw_circel_black)
                ivZjyq.setImageResource(R.mipmap.zhijianyaoqiu2)
                tvZjyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_white))

                ivProc.setBackgroundResource(R.color.color_transparent)
                ivProc.setImageResource(R.mipmap.gongyigongxu1)
                tvProc.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivllBwlf.setBackgroundResource(R.color.color_transparent)
                ivllBwlf.setImageResource(R.mipmap.buweiliangfa1)
                tvllBwlf.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivFzyq.setBackgroundResource(R.color.color_transparent)
                ivFzyq.setImageResource(R.mipmap.fengzhiyaoqiu1)
                tvFzyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))
                Glide.with(this)
                    .load(HttpsKitUtils.replaceHttpsUrl(dayWorkRecordBean?.field3?.split(",")?.get(0)))
                    .into(photoViewWork)
                imgIndex = 3
            }
            //工艺工序
            btnllProc -> {

                ivProc.setBackgroundResource(R.drawable.dw_circel_black)
                ivProc.setImageResource(R.mipmap.gongyigongxu2)
                tvProc.setTextColor(ContextCompat.getColor(baseContext, R.color.color_white))

                ivllBwlf.setBackgroundResource(R.color.color_transparent)
                ivllBwlf.setImageResource(R.mipmap.buweiliangfa1)
                tvllBwlf.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivFzyq.setBackgroundResource(R.color.color_transparent)
                ivFzyq.setImageResource(R.mipmap.fengzhiyaoqiu1)
                tvFzyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))

                ivZjyq.setBackgroundResource(R.color.color_transparent)
                ivZjyq.setImageResource(R.mipmap.zhijianyaoqiu1)
                tvZjyq.setTextColor(ContextCompat.getColor(baseContext, R.color.color_dada))
                Glide.with(this)
                    .load(HttpsKitUtils.replaceHttpsUrl(procItem?.img?.split(",")?.get(0)))
                    .into(photoViewWork)
                imgIndex = 4
            }
            llbtnProc -> {
                //如果多个工序 下拉列表
                if (listPopupWindow == null) {
                    showListPopWindow()
                }
                if (!listPopupWindow?.isShowing!!) {
                    listPopupWindow?.show()
                }
            }
            //扫码
            btnScanWork -> {
                showCameraWithPermissionCheck()
            }


        }
    }

    override fun setStatusBar() {
        StatusBarUtils.fullScreen(this)
    }

    /**
     * 初始化数据
     */
    private fun initData() {


        //todo判断是空页面进来，还是日生产计划进来

        day = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
        val qrCode = intent.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        empName = loginResultBean.empname
        recordViewModel = ViewModelProvider(this).get(WorkRecordViewModel::class.java)
        recordViewModel?.getPackData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it == null) {
                showToast(getString(R.string.text_not_find_pack))
            } else {
//                orderId = it.orderId
//                packId = it.packId
//                val jsonObject = JSONObject()
//                jsonObject.put("empId", empId);
//                jsonObject.put("empName", empName);
//                jsonObject.put("packId", it.packId);
//                jsonObject.put("packNo", it.packNO);
//                jsonObject.put("orderId", it.orderId);
//                jsonObject.put("styleNO", it.styleNO);
//                jsonObject.put("productName", it.productName);
//                jsonObject.put("color", it.color);
//                jsonObject.put("size", it.size);
//                jsonObject.put("quantity", it.quantity)
//                //新增 日生产计划
//                recordViewModel?.loadRecordData(jsonObject.toString())
//                showLoading()

            }

        })
        //日生产计划
        recordViewModel?.getWorkRecord()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it != null && it.size > 0) {
                dayWorkRecordBean = it.get(0)
                tvPackNoWork.text =
                    getString(R.string.text_pack_no) + " " + dayWorkRecordBean?.packNo
                tvStyleNameWork.text = dayWorkRecordBean?.productName
                tvSytleNoWork.text =
                    getString(R.string.text_style) + " " + dayWorkRecordBean?.styleNO
                tvNumWork.text = getString(R.string.text_amount) + " " + dayWorkRecordBean?.quantity
                tvColorWork.text = getString(R.string.text_color) + " " + dayWorkRecordBean?.color
                tvSizeoWork.text = getString(R.string.text_size) + " " + dayWorkRecordBean?.size
                if (dayWorkRecordBean?.list != null && dayWorkRecordBean?.list!!.size > 0) {
                    allStrList.clear()
                    if (dayWorkRecordBean?.list?.size == 1) {
                        procItem = dayWorkRecordBean?.list!!.get(0)

                    } else {
                        for (index in dayWorkRecordBean?.list!!.indices) {
                            if(TextUtils.isEmpty(dayWorkRecordBean?.list!!.get(index).finishTime)) {
                                procItem = dayWorkRecordBean?.list!!.get(index)
                            }else{
                                procItem = dayWorkRecordBean?.list!!.get( dayWorkRecordBean?.list!!.size-1)
                            }
                            allStrList.add(dayWorkRecordBean?.list!!.get(index))
                            arrayAdapter?.notifyDataSetChanged()
                        }
                    }
                    tvProcNameWork.text = procItem?.procName
                    if (!TextUtils.isEmpty(procItem?.finishTime)) {
                        tvStatusWork.text = getString(R.string.has_finished)
                    } else {
                        tvStatusWork.text = getString(R.string.has_begin)
                    }
                }

                imgIndex = 1
                btnllBwlf.performClick()
            }

        })
        //没有日计划的做工返回
        recordViewModel?.getNoPlanWorkResult()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
//            recordViewModel?.load
            //去查询 做工记录
            Handler().postDelayed(Runnable {
                recordViewModel?.loadDayRecord(empId, packId, orderId)
            }, 500)
        })

        recordViewModel?.getMessageData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
         })

        //一进页面查询最近数据
        recordViewModel?.loadDayRecordLast(empId);
        showLoading()

        recordViewModel?.getRecordData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it != null) {
                packId = it.packId
                orderId = it.orderId
                if (it.statusNum == 1) {
                    if (it.orderCraftprocessList != null && it.orderCraftprocessList.size > 0) {
                        //无法做工，没有日计划
                        var adapterList: MutableList<OrderCraftprocessBean> =
                            ArrayList<OrderCraftprocessBean>()
                        for (proc in it.orderCraftprocessList) {
                            adapterList.add(proc)
                        }
                        val builder: AlertDialog.Builder =
                            AlertDialog.Builder(DayWorkScanActivity@ this)
                        val procAapter = WorkRecordProcAdapter(
                            DayWorkScanActivity@ this,
                            adapterList
                        )
                        builder.setAdapter(procAapter, null).setNegativeButton(
                            getString(R.string.cancel),
                            DialogInterface.OnClickListener { dialog, which ->
                                Handler().postDelayed(Runnable {
                                    DisplayUtil.hideSystemNavigationBar(
                                        this
                                    )
                                }, 500)
                            }).setPositiveButton(getString(R.string.sure),
                            object : DialogInterface.OnClickListener {
                                override fun onClick(dialog: DialogInterface?, which: Int) {
                                    (it.orderCraftprocessList as MutableList<OrderCraftprocessBean>).clear()
                                    (it.orderCraftprocessList as MutableList<OrderCraftprocessBean>).add(
                                        adapterList.get(procAapter.selectPosition)
                                    )
                                    recordViewModel?.loadNoPlanWork(Gson().toJson(it));
                                    showLoading()
                                    Handler().postDelayed(Runnable {
                                        DisplayUtil.hideSystemNavigationBar(
                                            this@DayWorkScanActivity00
                                        )
                                    }, 500)
                                }
                            }).show()
                    } else {
                        showToast(getString(R.string.work_failed))
                    }
                } else if (it.statusNum == 2) {
                    //做工成功
                    if (it.states == "1"){
                        showToast(getString(R.string.work_start))
                    }else{
                        showToast(getString(R.string.work_end))
                    }

                    //去查询 做工记录
                    Handler().postDelayed(Runnable { recordViewModel?.loadDayRecord(empId, packId, orderId) },500)
                } else if (it.statusNum == 3) {
                    showToast(getString(R.string.work_failed))
                }else if(it.statusNum == 4){
                    showToast("该包已经做工，请重新扫码")
                }else if (it.statusNum == 5){
                    showToast("今天日计划已经暂停/停止,请联系班组长")
                }else if(it.statusNum == 6){
                    showToast("计划还在审批中，不能做工")
                }
            } else {
                showToast(getString(R.string.net_request_fail))
            }


        })

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        super.onCreate(savedInstanceState)
    }

    /**
     * 初始化view
     */
    private fun initView() {
        setContentView(R.layout.activity_work_scan)
        //强制横屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        btnReturnScanWork.setOnClickListener { finish() }

    }

    override fun onStart() {
        super.onStart()
        Handler().postDelayed(Runnable { DisplayUtil.hideSystemNavigationBar(this) }, 500)

    }


    override fun onResume() {
        super.onResume()
        DayWorkScanActivityShow = true;
        Log.e("DayWorkScanActivity", "onResume")
    }

    override fun onPause() {
        super.onPause()
        DayWorkScanActivityShow = false;
        Log.e("DayWorkScanActivity", "onPause")
    }

    /**
     * 初始化 popup
     */
    fun showListPopWindow() {
        listPopupWindow = ListPopupWindow(this);
        arrayAdapter = DayWorkScanProcAdapter00(this,allStrList)
        listPopupWindow?.setAdapter(arrayAdapter)
        listPopupWindow?.setAnchorView(llbtnProc);//设置listpopowindow和哪个控件相邻
//        listPopupWindow?.setModal(true);//指定listpopwindow是否阻止在显示的时候将内容输入其他窗口


        listPopupWindow?.setOnItemClickListener(object : AdapterView.OnItemClickListener {
            override fun onItemClick(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                tvProcNameWork.text = allStrList[position].procName
                procItem = dayWorkRecordBean?.list?.get(position)
                if (!TextUtils.isEmpty(procItem?.finishTime)) {
                    tvStatusWork.text = getString(R.string.has_finished)
                } else {
                    tvStatusWork.text = getString(R.string.has_begin)
                }
                if (imgIndex == 4) {
                    btnllProc.performClick()
                }
                listPopupWindow?.dismiss()
            }
        });
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
//            recordViewModel?.loadPackData(qrCode)

            val jsonObject = JSONObject()
            jsonObject.put("empId", empId);
            jsonObject.put("empName", empName)
            jsonObject.put("publicQRCode",qrCode)
            //新增 日生产计划
            recordViewModel?.loadRecordData(jsonObject.toString())
        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }


}
